﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Resources;
using System.Globalization;
using System.Reflection;
using FileHelpers.RunTime;
using FileHelpers.MasterDetail;
using FileHelpers.DataLink;
using FileHelpers;
using RaceScore.BusinessLayer;


namespace RaceScore
{
    public partial class Import_Participants_1 : Form
    {
        private Main myParent = null;
        private string filenameToOpen;
        private char? delimiter;
        private ComboBox[] fieldSelectors;

        public Import_Participants_1(Main myParent)
        {
            InitializeComponent();
            
            this.myParent = myParent;


            string[] fields = {"Choose Column", "Name", "Age", "Bib #", "Gender", 
                               "First Name", "Last Name", "Date of Birth"};

            fieldSelectors = new ComboBox[4];
            fieldSelectors[0] = comboBox1;
            fieldSelectors[1] = comboBox2;
            fieldSelectors[2] = comboBox3;
            fieldSelectors[3] = comboBox4;

            foreach (ComboBox c in fieldSelectors)
            {
                c.Items.AddRange(fields);
                c.SelectedIndex = 0;
                c.Visible = false;
            }

            dataPreview.Text = "";

            toggleDelimitChoice(false);
        }

        private void toggleDelimitChoice(bool enabledDisabled)
        {
            panel1.Enabled = enabledDisabled;
            skipFirstLineCB.Enabled = enabledDisabled;
            button1.Enabled = enabledDisabled;
        }



        private void openFileDialog1_FileOk(object sender, CancelEventArgs e)
        {

        }

        private void openFile_Click(object sender, EventArgs e)
        {

            OpenFileDialog openFile = new OpenFileDialog();

            //openFileDialog1.InitialDirectory = "c:\\";
            openFile.Filter = "csv files (*.csv)|*.csv|All files (*.*)|*.*";
            openFile.FilterIndex = 2;
            openFile.RestoreDirectory = true;

            if (openFile.ShowDialog() == DialogResult.OK)
            {
                filenameToOpen = (string)openFile.FileName;
                fileTextBox.Text = filenameToOpen;
                previewFile(null);
            }

        }


        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
            previewFile(',');
        }

        /// <summary>
        /// Displays the specified file in preview file window.
        /// 
        /// Delimits the file by the specified delimiter, if any.
        /// </summary>
        /// <param name="delimiter"></param>
        private void previewFile(char? _delimiter)
        {
            delimiter = _delimiter;

            StreamReader sr;

            try
            {
                sr = File.OpenText(filenameToOpen);
            }
            catch (Exception e)
            {
                MessageBox.Show(String.Format("Error opening file. Error: {1}", filenameToOpen, e.Message));
                toggleDelimitChoice(false);
                filenameToOpen = "";
                fileTextBox.Text = "";

                return;
            }

            toggleDelimitChoice(true);

            string input;
            int i = 0;
            bool containsDelimiter = false;
            string[] fields;
            dataPreview.Text = "";

            if (skipFirstLineCB.Checked == true)
                sr.ReadLine();

            while ((input = sr.ReadLine()) != null)
            {
                i++;

                if (_delimiter != null)
                {
                    ///TODO use CSV Engine instead of Split
                    fields = input.Split((char)delimiter);

                    if (fields.Length > 1)
                        containsDelimiter = true;

                    foreach (string field in fields)
                    {
                        dataPreview.Text += String.Format("{0,-15}", field);
                        //dataPreview.Text += "\t|\t";
                    }
                }
                else
                {
                    dataPreview.Text += input;
                }

                dataPreview.Text += Environment.NewLine;
                
                if (i > 10)
                {
                    break;
                }
            }

            foreach (ComboBox c in fieldSelectors)
            {
                c.Visible = containsDelimiter;
            }
            
        }

        private static List<Participant> PopDummyParticipants()
        {
            List<Participant> Participants = new List<Participant>();
            Participants.Add(new Participant("Jeff Huber", 101, 29));
            return Participants;
        }

        /// <summary>
        /// Parse file and insert into db
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="ea"></param>
        private void button1_Click(object sender, EventArgs ea)
        {
            StreamReader sr;

            if (delimiter == null)
            {
                MessageBox.Show("You have not choosen a delimiter.");
                return;
            }

            try
            {
                sr = File.OpenText(filenameToOpen);
            }
            catch (Exception e)
            {
                MessageBox.Show(String.Format("Error opening file. Error: {1}", filenameToOpen, e.Message));
                toggleDelimitChoice(false);
                filenameToOpen = "";
                fileTextBox.Text = "";

                return;
            }

            List<Participant> Participants = new List<Participant>();

            toggleDelimitChoice(true);

            string input;
            //bool containsDelimiter = false;
            string[] fields;


            if (skipFirstLineCB.Checked == true)
                sr.ReadLine();

            while ((input = sr.ReadLine()) != null)
            {
                ///TODO use CSV Engine instead of Split
                fields = input.Split((char)delimiter);

                ///TODO choose fields based on drop-downs
                Participant p   = new Participant();
                p.Bib           = Int32.Parse(fields[0]);
                p.Name          = fields[1];
                p.Gender        = fields[2].ToCharArray()[0];
                p.Age           = Int32.Parse(fields[3]);

                Participants.Add(p);
            }

            MessageBox.Show(Participants.Count + " participants added");
            Program.CurrentRace.Participants = Participants;

            myParent.UpdateParticipantsGrid();   

            Close();
        }

        private void comma_CheckedChanged(object sender, EventArgs e)
        {
            previewFile(',');       
        }

        private void space_CheckedChanged(object sender, EventArgs e)
        {
            previewFile(' ');
        }

        private void tab_CheckedChanged(object sender, EventArgs e)
        {
            previewFile('\t');
        }

        private void other_CheckedChanged(object sender, EventArgs e)
        {
            if (otherDelimiter.Text.ToCharArray().Length == 0)
                return;

            previewFile(otherDelimiter.Text.ToCharArray()[0]);
           
        }

        private void otherDelimiter_TextChanged(object sender, EventArgs e)
        {
            if (other.Checked == false || (otherDelimiter.Text.ToCharArray().Length == 0))
                return;

            previewFile(otherDelimiter.Text.ToCharArray()[0]);

        }

        private void skipFirstLineCB_CheckedChanged(object sender, EventArgs e)
        {
            previewFile(delimiter);
        }



    }
}
